package com.java.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 * 
 * @author Kevin
 *
 */
public class DateTools {

	/**
	 * 传入初始时间和结束时间，计算两时间间周末的总时长
	 * 
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public static long calWeekendTime(Date beginTime, Date endTime) {
		Calendar beginCal = Calendar.getInstance();
		beginCal.setTime(beginTime);
		// 是否为同一天
		if (isOneDay(beginTime, endTime)) {
			if (isWeekend(beginCal)) {
				return endTime.getTime() - beginTime.getTime();
			} else {
				return 0l;
			}
		} else {
			// 起始时间比终止时间小，用递归每天加一天计算,且是周末，计算当天到明天的时间
			if (beginTime.getTime() < endTime.getTime()) {
				long time = 0l;
				if (isWeekend(beginCal)) {
					beginCal.add(Calendar.DATE, 1);
					
					// 如果第二天也是周末，返回一整天的时间
					if (isWeekend(beginCal)) {
						time = oneDayTime();
					} else {
						// 如果不是获取第二天的凌晨的时间
						beginCal.set(Calendar.HOUR_OF_DAY, 0);
						beginCal.set(Calendar.MINUTE, 0);
						beginCal.set(Calendar.SECOND, 0);
						beginCal.set(Calendar.MILLISECOND, 0);
						time = beginCal.getTime().getTime() - beginTime.getTime();
					}
				}else{
					beginCal.add(Calendar.DATE, 1);
					// 如果第二天是周末，返回第二天到凌晨的时间
					if (isWeekend(beginCal)) {
						Date tempDate = beginCal.getTime();
						// 获取第二天的凌晨的时间
						beginCal.set(Calendar.HOUR_OF_DAY, 0);
						beginCal.set(Calendar.MINUTE, 0);
						beginCal.set(Calendar.SECOND, 0);
						beginCal.set(Calendar.MILLISECOND, 0);
						time = tempDate.getTime() - beginCal.getTime().getTime();
					}
				}
				//时间增加一天，递归返回
				return time + calWeekendTime(new Date(beginTime.getTime() + oneDayTime()), endTime);
			} else {
				return 0l;
			}
		}
	}

	/**
	 * 一天的时间
	 * 
	 * @return
	 */
	public static long oneDayTime() {
		return 24 * 3600 * 1000l;
	}

	/**
	 * 是否为周末
	 * 
	 * @param beginCal
	 * @return
	 */
	public static boolean isWeekend(Calendar beginCal) {
		return (beginCal.get(Calendar.DAY_OF_WEEK) == 1 || beginCal.get(Calendar.DAY_OF_WEEK) == 7);
	}

	/**
	 * 是否为同一天
	 * 
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static boolean isOneDay(Date time1, Date time2) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(time1).equals(sdf.format(time2));
	}

	public static void main(String[] args) throws Exception {
		String date1 = "2018-10-18 12:00:00";
		String date2 = "2018-10-21 12:00:00";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date time1 = sdf.parse(date1);
		Date time2 = sdf.parse(date2);
		long time = calWeekendTime(time1, time2);
		System.out.println(time / (24 * 3600 * 1000d));
	}

}
